package com.zhouyu.exampledesignmoudle.proxy.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @description: cglib代理
 * @author: zhouyu
 * @create: 2020-05-09 09:16
 */
public class CglibProxyHandler implements MethodInterceptor {
    private Object target;

   /**
   * @description :
   * @param obj: 代理对象
   * @param method: 目标方法
   * @param objects: 目标方法参数
   * @param methodProxy: 代理目标方法
   * @return {@link Object}
   * @author zhouyu
   * @date 2020/5/9 10:44
   */
    @Override
    public Object intercept(Object obj, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        doBefore();
        /**
         * methodProxy.invokeSuper(obj, objects),代理类对调用的每个方法都会增强,当然每个方法是public的才可以
         * method.invoke(target, objects),代理类仅仅只会对直接代理的方法增强，对代理对象的其他方法不会增强
         */
        //Object result = methodProxy.invokeSuper(obj, objects);
        Object result = method.invoke(target, objects);
        doAfter();
        return result;
    }

    /**
    * @description :创建代理对象
    * @param target: 目标对象
    * @return {@link Object}
    * @author zhouyu
    * @date 2020/5/9 10:43
    */
    public Object bind(Object target) {
        this.target = target;
        Enhancer en = new Enhancer();
        en.setSuperclass(target.getClass());
        en.setCallback(this);
        return en.create();
    }

    private void doAfter() {
        System.out.println("cglib after method invoke...");
    }

    private void doBefore() {
        System.out.println("cglib before method invoke...");
    }
}
